package cn.tedu.sp06.controller;

import cn.tedu.sp01.pojo.Item;
import cn.tedu.sp01.util.JsonResult;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@RestController
@Slf4j
@EnableCircuitBreaker
public class RibbonController {
    @Autowired
    private RestTemplate rt;

    @HystrixCommand(fallbackMethod = "getItemsFB")
    @GetMapping("/item-service/{orderId}")
    public JsonResult<List<Item>> getItems(@PathVariable String orderId){

        //RestTemplate必须给出具体的地址
        //{1}{2}是RestTemplate提供的占位符
        return rt.getForObject("http://item-service/{1}",JsonResult.class,orderId );

    }

    @PostMapping("/item-service/decreaseNumber")
    @HystrixCommand(fallbackMethod = "decreaseNumberFB")
    public JsonResult<?> decreaseNumber(@RequestBody List<Item> items){
        return rt.postForObject("http://item-service/decreaseNumber", items,JsonResult.class);
    }

    public JsonResult<List<Item>> getItemsFB(String orderId){
        // 上面的方法中，调用远程服务失败
        // 执行这里的降级代码，直接向客户端返回响应
        return JsonResult.err().msg("调用商品服务信息失败");

    }
    public JsonResult<?> decreaseNumberFB(List<Item> items){
        return JsonResult.err().msg("调用商品服务信息失败");
    }
}
